local M = {}

local id2user = {}
local account2user = {}
local log = require("log"):new("user_mgr")
local count = 0

-- return false is already exist
function M.insert(user)
	assert(user)
	local rpc_clt_id = user.rpc_clt_id
	if id2user[rpc_clt_id] then
		return false
	end
	local account = user.account
	if account2user[account] then
		return false
	end

	id2user[rpc_clt_id] = user
	account2user[account] = user
	count = count + 1
	log:debug("Inserted. rpc_clt_id=%u, now_count=%d", rpc_clt_id, count)
	return true
end  -- insert()

function M.erase(rpc_clt_id)
	if not rpc_clt_id then return end
	local user = id2user[rpc_clt_id]
	if not user then return end

	user.timer_queue:erase_all();  -- 主动清定时器，因为user对象可能会延时删除
	id2user[rpc_clt_id] = nil
	account2user[user.account] = nil
	count = count - 1
	log:info("Erased. rpc_clt_id=%u, now_count=%d", rpc_clt_id, count)
end  -- erase()

--[[
function M.erase(account)
	if not account then return end
	local user = account2user[account]
	if not user then return end
	id2user[account] = nil
	account2user[user.rpc_clt_id] = nil
	count = count - 1
	log:info("Erased. rpc_clt_id=%u, now_count=%d", rpc_clt_id, count)
end  -- erase()
]]

function M.get_user(rpc_clt_id)
	if not rpc_clt_id then return nil end
	return id2user[rpc_clt_id]
end

function  M.get_user_account(rpc_clt_id)
    if not rpc_clt_id then return nil end
    local user = id2user[rpc_clt_id]
    if not user then return end
    return user.account
end

function M.get_rpc_clt_id(account)
	if not account then return end
	local user = account2user[account]
	if not user then return end
	return user.rpc_clt_id
end

function M.get_count()
	return count
end

return M
